C++ union 与 reinterpret_cast
全部标签 如果我有这样的标准布局类型:structsl_t{inta;};像这样的union:unionun_t{intb;doubleq;};我可以转换并使用union作为结构类型吗?也就是说,我可以假设union本身是标准布局类型并且数据在内存的开头对齐吗?un_tobj;sl_t*s=reinterpret_cast(&obj);s->a=15;assert(obj.b==15);或者我必须取union体&obj.b中变量的地址吗?请注意,我已经知道如果我将结构存储在union中,C++11标准保证我可以访问sl_t::a和un_t::b,引用9.5-1。 最佳
从unsignedint的vectorvector开始...vector>matrix;vectorrow;我想合并union集(即具有共同元素的vector)。例如,作为输入:matrix[0]={0,1,2}matrix[1]={1,10}matrix[3]={9}matrix[4]={2,8}matrix[5]={7}作为输出:matrix[0]={0,1,2,10,8}//itdoesn'tmattertheordermatrix[1]={9}matrix[2]={7}对于这个问题,哪个是最有效的解决方案?最好的问候,Vi。 最佳答案
我刚刚在读Stroustrup的新书。在第22.2.2章中,他讨论了dynamic_cast问题。我自己写的测试代码如下:classStorable{public:inti;virtualvoidr(){};Storable(){i=1;};};classComponent:publicvirtualStorable{public:Component(){i=1;};};classReceiver:publicComponent{public:Receiver(){i=2;};};classTransmitter:publicComponent{public:Transmitter()
我正在实现一个“变体”类,它必须具有尽可能小的内存占用并使用共享指针机制存储一些对象。为此,我想在所有变量类型的类中建立一个union。这包括一些shared_ptr。operator=和复制构造函数必须更改变量的数据类型,从而切换到union中的另一个成员。切换到shared_ptr后,应将其重置为null而无需删除/取消拥有指针。有办法做到这一点吗?当然,还有其他方法可以实现这一点,但在我的例子中,它们通常更复杂、更不安全或消耗更多内存。不过欢迎提出任何建议。谢谢! 最佳答案 重置为null是不够的;的实现std::shared
来自thisquestion我了解到匿名结构和union已成为C11标准的一部分(来自评论)。然后我想用bitfieldunion来代替bitmask可能是个好主意,我发现其他人已经发布了一个问题并显示了anexample。,这和我的想法完全一样。该问题的答案同意使用位域union方法替换位掩码的安全性。但是,thepostthere的答案,据我了解,否认访问不活跃的union成员的安全性,说访问不活跃的union成员是未定义的行为。我认为这两个问题的答案是矛盾的:仅使用theexamplethere,在修改.user后,.raw的值会变成undefined(通过对thepost的回答
我正在编写一个简单的包装类,我想为包装类型提供显式转换运算符。以下代码使用gcc编译良好classwrap{doublevalue;public:explicitwrap(doublex):value(x){}explicitoperatordouble&&()&&{returnstd::move(value);}};intmain(){wrapw(5);double&&x(std::move(w));//okdouble&&y=static_cast(std::move(w));//clangreportsanerrorhere}但是clang报告error:cannotcastfr
人们说相信reinterpret_cast将原始数据(如char*)转换为结构是不好的。例如,对于结构structA{unsignedinta;unsignedintb;unsignedcharc;unsignedintd;};sizeof(A)=16和__alignof(A)=4,完全符合预期。假设我这样做:char*data=newchar[sizeof(A)+1];A*ptr=reinterpret_cast(data+1);//+1istoensureitdoesn'tpointsto4-bytealigneddata然后复制一些数据到ptr:memcpy_s(sh,sizeo
这个简短的C++程序的行为方式让我感到困惑:#include#include#include#includeintmain(void){signedcharc=-2;assert(c==-2);c=boost::lexical_cast(std::string("-2"));std::cout使用g++5.2.1和boost-1.58.0,我得到:terminatecalledafterthrowinganinstanceof'boost::exception_detail::clone_impl>'what():badlexicalcast:sourcetypevaluecouldn
最近,我在这里阅读了range-v3的提交评论:https://github.com/ericniebler/range-v3/commit/a4829172c0d6c43687ba213c54f430202efd7497提交消息说,marginallyimprovecompiletimesbyreplacingstd::forwardwithstatic_cast我知道std::forward(t)返回static_cast(t),按照标准。我也知道有时static_cast(t)当T&&t时会正常工作是通过引用折叠规则的通用引用(或转发引用)。我感兴趣的是提交消息说static_c
假设有一个这样的枚举:enumfoo:int{first,second}然后我使用它如下:foof(1);//error:cannotinitializeavariableoftype'foo'withanrvalueoftype'int'foof=foo(1);//OK!我想知道这两者有什么区别?我知道第二个版本可以看作是函数式转换,但为什么这会有什么不同?例如,如果我这样做:classBar{};Barb=Bar(1);//nomatchingconversionforfunctional-stylecastfrom'int'to'Bar'我显然得到了一个有意义的错误。因此,这让我